<?php

namespace app\common\controller;

use app\BaseController;
use app\common\component\Session;
use app\common\component\OssClients;

//use app\common\model\Material;

/**
 * 文件上传
 * @author guoyong
 *
 */
class Upload extends BaseController
{

    protected $allow = ['jpg', 'jpeg', 'png', 'gif', 'zip', 'rar', 'mp3', 'swf'];

    protected $path = [
        'img' => [
            'path' => './uploads/images/',
            'maxsize' => 100 //M
        ],
        'sound' => [
            'path' => './uploads/sound/',
            'maxsize' => 2 //M
        ],
        'file' => [
            'path' => './uploads/file/',
            'maxsize' => 100
        ],
        'video' => [
            'path' => './uploads/video/',
            'maxsize' => 100
        ]
    ];


    protected function _initialize()
    {
        // if(empty($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'] , SERVER_PATH) === false){
        //     ajaxError('错误的操作');
        // }

        $path = explode('/', $_SERVER['HTTP_REFERER']);
        $moduel = strtolower(end($path));
        if (in_array($moduel, ['admin', 'manage'])) {
            if ($moduel == 'admin') {
                $user = session(Session::ADMIN_LOGIN_INFO);
            } else {
                $user = session(Session::MANAGE_LOGIN_INFO);
            }
            if (empty($user))
                ajaxError('请登陆再上传');
        }
    }
    public function uploadFile()
    {
        if (empty($_FILES))
            return error('没有文件上传');
        foreach ($_FILES as $file) {
            if ($file['error']) {
                return error('文件上传失败');
            }
            $extName = ltrim(strtolower(strrchr($file['name'], '.')), '.');
            $name = (date('YmdHis')). '_' . (rand(1000, 9999)) . '.' . $extName;
            $path = $this->getPath('file');
            $filename = $path.$name;

            move_uploaded_file($file['tmp_name'], $filename);
            $filename = $this->request->domain(). ltrim($filename, '.');
            $data = [
                'state' => 'SUCCESS',
                'type' => '.' . $extName,
                'url' => $filename
            ];
        }
         ajaxSuccess($data);

    }
    /**
     * 上传base64文件
     */
    public function uploadBase()
    {
        $code = input('request.code');
        $suffix = input('request.suffix');
        $type = input('request.type');
        $full = intval(input('request.full', 0));
        if (!isset($this->path[$type]))
            ajaxError('请指定上传文件类型');
        if (empty($suffix)) {
            $suffix = $type == 'img' ? 'jpg' : 'mp3';
        }
        $this->verifySuffix($suffix);
        $code = str_replace(" ", "+", $code);
        $code = preg_replace('/^data:.*base64,/', '', $code);

        $this->verifyMaxsize($code, $type);

        $path = $this->getPath($type);

        $name = (date('YmdHis')) . '_' . (rand(100, 999)) . '.' . $suffix;
        $filename = $path . $name;
        file_put_contents($filename, base64_decode($code));
 		$filename = ltrim( $filename , '.' );
        $result = [];
        $result['path'] = $this->request->domain().$filename;
        $result['view'] = $this->request->domain().$filename;
        ajaxSuccess($result);
    }

    private function getPath($type)
    {
        $path = $this->path[$type]['path'] . date('Ym') . '/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        return $path;
    }

    private function verifySuffix($suffix)
    {
        if (!in_array(strtolower($suffix), $this->allow)) {
            ajaxError('不被允许的文件类型');
        }
        return true;
    }

    private function verifyMaxsize($code, $type)
    {
        $maxSize = $this->path[$type]['maxsize'] * 1024 * 1024;
        if (strlen($code) > $maxSize) {
            ajaxError('上传的文件超出限制,请重新调整图片大小，只能上传' . $this->path[$type]['maxsize'] . 'M');
        }
        return true;
    }


}

